#include "ACBuilder.h"
#include "Utils.h"
#include "acprotocol.h"
#include <QDebug>

#define BYTE_HEADER  0
#define BYTE_PKG_LEN_H   1
#define BYTE_PKG_LEN_L   2
#define BYTE_PKG_ID      3
#define BYTE_ACODE       4
#define BYTE_FCODE       5
#define BYTE_DATA_BASE   6

#define PKG_MIX_LEN    8



ACBuilder  ACBuilder::mInstance;

ACBuilder::ACBuilder()
{

}

ACBuilder *ACBuilder::getInstance()
{
    return &mInstance;
}

void ACBuilder::buildPackage(uint8_t pkgId, uint8_t attachCode, uint8_t funCode, uint8_t *data, uint16_t size)
{
    mPackage.pkgLength  = PKG_MIX_LEN;
    int      dataEndIndex  = BYTE_DATA_BASE;
    mPackageBytes[BYTE_HEADER]  = AC_PKG_HEADER;
    mPackageBytes[BYTE_PKG_ID]  = pkgId;
    mPackageBytes[BYTE_ACODE]   = attachCode;
    mPackageBytes[BYTE_FCODE]   = funCode;

    if(size > 0){
        memcpy(&mPackageBytes[BYTE_DATA_BASE], data, size);
        mPackage.pkgLength  += size;
        dataEndIndex  = BYTE_DATA_BASE + size;
    }

    mPackageBytes[BYTE_PKG_LEN_H]  = (mPackage.pkgLength >> 8) & 0xff;
    mPackageBytes[BYTE_PKG_LEN_L]  = mPackage.pkgLength & 0xff;

    uint8_t sum  = Utils::calcSum(mPackageBytes, dataEndIndex +1);
    mPackageBytes[dataEndIndex]  = sum;
    mPackageBytes[dataEndIndex+1]  = AC_PKG_TAIL;

    QString text;
    Utils::hexArray2String(mPackageBytes, mPackage.pkgLength, text);
    qDebug() << text;
}


void ACBuilder::buildPackage(ACPackage& pkg)
{
    buildPackage(pkg.pkgId, pkg.attachCode, pkg.funCode, pkg.payloadData, pkg.payloadSize);
}

void ACBuilder::buildPackage()
{
    buildPackage(mPackage);
}

uint16_t ACBuilder::dumpPackage(uint8_t *buf)
{
    memcpy(buf, mPackageBytes, mPackage.pkgLength);
    return mPackage.pkgLength;
}



